package com.ruoyi.business.service.impl;

import com.aliyun.oss.model.PutObjectRequest;
import com.ruoyi.business.mapper.TiffSegMapper;
import com.ruoyi.business.utils.OSSUtil;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.system.service.ISysConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
public class TiffProcessService {

    Logger logger = LoggerFactory.getLogger(TiffProcessService.class);

    @Autowired
    private TiffSegMapper tiffSegMapper;

    @Autowired
    private ISysConfigService configService;

    @Value("${ruoyi.tiffSeg}")
    private String tiffSegPath;

    @Value("${oss.seg_bucket}")
    private String seg_bucket;

//    @Value("${oss.endpoint}")
//    private String endpoint;
//
//    @Value("${oss.region}")
//    private String region;
//
//    @Value("${oss.accessKeyId}")
//    private String accessKeyId;
//
//    @Value("${oss.accessKeySecret}")
//    private String accessKeySecret;

    @Value("${oss.ossTargetDirectory}")
    private String ossTargetDirectory;

    @Value("${oss.defaultRegion}")
    private String defaultRegion;

    @Async("taskExecutor")
    public void processImage(String fileName, Long id) {
        LocalDateTime localDate = LocalDateTime.now();
        UUID uuid = UUID.randomUUID();

        // 文件名称
        String objectName = localDate.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) + "_" + uuid;

        // 使用Libvips命令行工具处理
        String[] cmd = {
                "vips", "dzsave",
                fileName,
                tiffSegPath + objectName + "/" + objectName
        };

        logger.info("开始切片数据ID为 {} 的文件：{}, 执行的命令为：{}", id, fileName, String.join(" ", cmd));
        // 下载文件到临时目录

        try {
            // 执行转换
            Process process = Runtime.getRuntime().exec(cmd);
            process.waitFor();

            logger.info("数据ID为 {} 的文件切片完成!, 并且开始上传切片文件", id);
            Path directoryPath = new File(tiffSegPath + objectName).toPath();

            // 遍历目录中的所有文件
            Files.walkFileTree(directoryPath, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
                    // 获取相对于源目录的相对路径
                    String relativePath = directoryPath.relativize(file).toString();
                    relativePath = relativePath.replace("\\", "/");
                    // 构建OSS上的完整路径
                    String ossObjectKey = ossTargetDirectory + relativePath;

                    // 等指令执行完毕后，将切分好的文件上传到OSS中
                    OSSUtil ossUtil = new OSSUtil(configService.selectConfigByKey("endpoint"), configService.selectConfigByKey("region"), configService.selectConfigByKey("accessKeyId"), configService.selectConfigByKey("accessKeySecret"));

                    boolean uploadFile = ossUtil.uploadFile(seg_bucket, ossObjectKey, file.toFile());

                    // 将dzi文件的objectName存储在数据库中
                    if (relativePath.endsWith(".dzi")) {
                        tiffSegMapper.updateDziObjectName(ossObjectKey, id);
                    }


                    if (!uploadFile) {
                        logger.error("tiff切割文件上传阿里云OSS失败！");
                        return FileVisitResult.TERMINATE;
                    }

                    // 将上传完的文件删除掉
                    file.toFile().delete();

                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFileFailed(Path file, java.io.IOException exc) {
                    System.err.println("Failed to visit file: " + file.toString());
                    return FileVisitResult.CONTINUE;
                }
            });

            logger.info("数据ID为 {} 的切片文件上传完成!", id);
            // 修改Tiff文件是否已分割完成的状态
            tiffSegMapper.updateIsSeg(id, 1);

            // 删除切边文件夹
            File directory = new File(tiffSegPath + objectName);
            if (directory.exists()) {
                deleteDirectory(directory);
            }

            // 切片文件上传完成后将本地的缓存文件删除
//            File originFile = new File(fileName);
//            if (originFile.exists()) {
//                originFile.delete();
//            }

        } catch (Exception e) {
            logger.error("tiff文件切割失败！", e);
        }
    }

    private void deleteDirectory(File directory) {
        if (directory.exists()) {
            File[] files = directory.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isDirectory()) {
                        deleteDirectory(file);
                    } else {
                        file.delete();
                    }
                }
            }
            directory.delete();
        }
    }
//    public static void main(String[] args) {
//
//        LocalDateTime localDate = LocalDateTime.now();
//        UUID uuid = UUID.randomUUID();
//
//        // 文件名称
//        String objectName = localDate.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) + "_" + uuid;
//
//        String tiffSegPath = "D:/temp/";
//
//        // 使用Libvips命令行工具处理
//        // vips tiffsave input.tif output.dzi --tile --pyramid --compression=jpeg
//        String[] cmd = {
//                "vips", "dzsave",
//                "D:/tiff/input.tif",
//                tiffSegPath + objectName + "/" + objectName
//        };
//
//        try {
//            // 执行转换
//            Process process = Runtime.getRuntime().exec(cmd);
//            process.waitFor();
//            Path directoryPath = new File(tiffSegPath + objectName).toPath();
//            // 遍历目录中的所有文件
//            Files.walkFileTree(directoryPath, new SimpleFileVisitor<Path>() {
//                @Override
//                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
//                    // 获取相对于源目录的相对路径
//                    String relativePath = directoryPath.relativize(file).toString();
//                    System.out.println("relativePath : " + relativePath);
//                    return FileVisitResult.CONTINUE;
//                }
//
//                @Override
//                public FileVisitResult visitFileFailed(Path file, java.io.IOException exc) {
//                    System.err.println("Failed to visit file: " + file.toString());
//                    return FileVisitResult.CONTINUE;
//                }
//            });
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
}
